package com.dengxian.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dengxian.usercenter.common.BaseResponse;
import com.dengxian.usercenter.common.ErrorCode;
import com.dengxian.usercenter.common.ResultUtils;
import com.dengxian.usercenter.exception.BusinessException;
import com.dengxian.usercenter.model.VO.UserVO;
import com.dengxian.usercenter.model.domain.Im;
import com.dengxian.usercenter.model.domain.User;
import com.dengxian.usercenter.service.ImService;
import com.dengxian.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/im")
@Slf4j
@CrossOrigin(origins = {"http://match.dengxian.space/"}, allowCredentials = "true")
public class ImController {
    @Resource
    private ImService imService;

    @Resource
    private UserService userService;

    /**
     * 获取历史消息
     * @param limit
     * @return
     */
    @GetMapping("/init/{limit}")
    public BaseResponse<List<Im>> findAllInit(@PathVariable Integer limit) {
        List<Im> ims = imService.list(new QueryWrapper<Im>().orderByDesc("id").last("limit " + limit));
        return ResultUtils.success(ims.stream().sorted(Comparator.comparing(Im::getId)).collect(Collectors.toList()));
    }

//    /**
//     * 获取当前登录用户与某个用户的聊天记录
//     * @param messagesUserRequest
//     * @param request
//     * @return
//     */
//    @GetMapping("/user/messages")
//    public BaseResponse<List<Im>> findUserMessages(MessagesUserRequest messagesUserRequest, HttpServletRequest request) {
//        //校验参数是否为空
//        if (messagesUserRequest == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        if (request == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        //从请求中获取当前登录用户
//        User loginUser = userService.getLoginUser(request);
//        List<Im> oneMessages = imService.userMessagesList(messagesUserRequest, loginUser);
//        return ResultUtils.success(oneMessages);
//    }

    /**
     * 获取与登录用户有聊天记录用户列表
     * @param request
     * @return
     */
    @GetMapping("/chat/users")
    public BaseResponse<List<UserVO>> chatUserList(HttpServletRequest request) {
        //校验参数是否为空
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //从请求中获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        List<UserVO> userList = imService.listUsers(loginUser);
        return ResultUtils.success(userList);
    }
}
